﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using HengTong.Model._Admin;
using HengTong.Model.Db.Hr;
using HengTong.Model.Db.System;
using Microsoft.EntityFrameworkCore;
using TiaoTaoHelper.Wtm.Models;
using UUIDNext;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;

namespace HengTong.ViewModel.Person.SysPersonVms;

public partial class SysPersonImportVm : BaseImportVM<SysPersonTemplateVm, SysPerson>
{
    public async Task<bool> BatchSaveDataAsync()
    {
        var transaction = DC.BeginTransaction();
        try
        {
            SetEntityList();
            //查询工号重复的数据
            /*var staffNoDuplicates = EntityList
                .GroupBy(x => x.StaffNo)
                .Where(g => g.Count() > 1)
                .SelectMany(g => g)
                .ToList();
            if (staffNoDuplicates.Any())
            {
                MSD.AddModelError(" ", "工号重复: " + string.Join(", ", staffNoDuplicates.Select(x => x.StaffNo)));
                return false;
            }*/
            var userList = new List<FrameworkUser>();
            var positions = await DC.Set<SysJobPosition>()
                .AsNoTracking()
                .Include(e => e.Group)
                .Include(e => e.Roles)
                .ThenInclude(e => e.Role)
                .ToListAsync();
            foreach (var entity in EntityList)
            {
                if (string.IsNullOrWhiteSpace(entity.Phone))
                {
                    entity.Phone = null;
                    continue;
                }

                entity.ID = Uuid.NewDatabaseFriendly(Database.SqlServer);
                var user = new FrameworkUser
                {
                    ID = Uuid.NewDatabaseFriendly(Database.SqlServer),
                    ITCode = entity.StaffNo,
                    Name = entity.Name,
                    CellPhone = entity.Phone,
                    GroupId = entity.GroupId,
                    Password = Utils.GetMD5String(Uuid.NewDatabaseFriendly(Database.SqlServer).ToString()),
                    PersonId = entity.ID,
                    CreateBy = Wtm.LoginUserInfo?.ITCode,
                    UpdateBy = Wtm.LoginUserInfo?.ITCode,
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now
                };
                userList.Add(user);
                var position = positions
                    .FirstOrDefault(e => e.GroupId == user.GroupId && e.Name.Contains("职员"));
                if (position == null)
                {
                    // 赋予默认角色
                    var frameworkUserRoles = new FrameworkUserRole
                    {
                        ID = Uuid.NewDatabaseFriendly(Database.SqlServer),
                        UserCode = user.ITCode,
                        RoleCode = "102",
                        CreateBy = user.ITCode,
                        CreateTime = DateTime.Now,
                        UpdateBy = user.ITCode,
                        UpdateTime = DateTime.Now
                    };
                    await DC.Set<FrameworkUserRole>().AddAsync(frameworkUserRoles);
                }

                if (position != null)
                {
                    var userPosition = new SysUserJobPosition()
                    {
                        ID = Uuid.NewDatabaseFriendly(Database.SqlServer),
                        UserId = user.ID,
                        JobPositionId = position.ID,
                        IsMain = true
                    };
                    await DC.Set<SysUserJobPosition>().AddAsync(userPosition);
                    //添加岗位角色关联
                    foreach (var element in position.Roles)
                    {
                        var role = new FrameworkUserRole
                        {
                            ID = Uuid.NewDatabaseFriendly(Database.SqlServer),
                            RoleCode = element.Role.RoleCode,
                            TenantCode = element.Role.TenantCode,
                            UserCode = user.ITCode,
                            CreateBy = user.ITCode,
                            CreateTime = DateTime.Now,
                            UpdateBy = user.ITCode,
                            UpdateTime = DateTime.Now
                        };
                        await DC.Set<FrameworkUserRole>().AddAsync(role);
                    }

                    //添加岗位部门关联
                    var group = new FrameworkUserGroup
                    {
                        UserCode = user.ITCode,
                        GroupCode = position.Group.GroupCode,
                        TenantCode = position.Group.TenantCode,
                        CreateBy = user.ITCode,
                        CreateTime = DateTime.Now,
                        UpdateBy = user.ITCode,
                        UpdateTime = DateTime.Now
                    };
                    await DC.Set<FrameworkUserGroup>().AddAsync(group);
                }

                entity.CreateBy = user.ITCode;
                entity.CreateTime = DateTime.Now;
                entity.UpdateBy = user.ITCode;
                entity.UpdateTime = DateTime.Now;
            }

            await DC.Set<SysPerson>().AddRangeAsync(EntityList);
            await DC.Set<FrameworkUser>().AddRangeAsync(userList);
            await DC.SaveChangesAsync();
            await transaction.CommitAsync();
            return true;
        }
        catch (Exception e)
        {
            await transaction.RollbackAsync();
            MSD.AddModelError(" ", "导入失败: " + e.Message);
            return false;
        }
        finally
        {
            await transaction.DisposeAsync();
        }
    }
}